/*
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-12-05 10:10:43
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2024-12-06 14:44:10
 * @FilePath: \liuyanggui\src\cuselement-ui\cus-message\method.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { render, h } from "vue";
import { MessagePropsType, MessageContext } from "./types";
import MessageConstructor from "./index.vue";

/**
 * shallowReactive用于创建浅层响应式对象。它只处理对象的最外层属性的响应式，嵌套的数据不会被转化为响应式。
 */
// 创建存放组件实例的数组
const instances: MessageContext[] = shallowReactive([])

let seed = 1

export const createMessage = (props: MessagePropsType) => {

  const id = `message_${seed++}`
  // 创建dom元素
  const container = document.createElement("div");

  // 移除节点
  const destory = () => {
    const idx = instances.findIndex(instance => instance.id == id)
    if (idx == -1) return
    instances.splice(idx, 1)
    render(null, container);

  };

  const newProps = {
    ...props,
    onDestroy: destory,
    id,
  };

  // 创建虚拟dom节点
  const vnode = h(MessageConstructor, newProps);

  // 渲染dom
  render(vnode, container);

  // 将dom元素添加到页面中
  document.body.appendChild(container.firstElementChild!);

  const vm = vnode.component!
  // 创建组件实例
  const instance = {
    id,
    vnode,
    props: newProps,
    vm
  }

  instances.push(instance)
  // 返回实例
  return instance
};

// 获取最后一个实例
export const getLastInstance = () => {
  return instances[instances.length - 1]
}

//获取上一个实例最下面的坐标位置
export const getLastBottomOffset = (id: string) => {
  const idx = instances.findIndex(instance => instance.id == id)
  if (idx <= 0) {
    return 0
  } else {
    const prev = instances[idx - 1]
    return prev.vm.exposed!.bottomOffest.value
  }
}